<template>
  <el-tree
      ref="treeRef"
      :props="treeProps"
      :check-strictly="true"
      :data="menuTree"
      node-key="id"
      show-checkbox
      :check-on-click-node="true"
      default-expand-all
      :expand-on-click-node="false"
      :default-checked-keys="checkedKeys"
      @check-change="checkChange"
  />
  <el-divider/>
  <el-button plain @click="handleClose">取消</el-button>
  <el-button type="primary" plain @click="handleSubmit">确定</el-button>
</template>

<script setup lang="ts">
import {nextTick, onMounted, ref, watch} from "vue";
import useMenuStore from "@/store/menu";
import {RoleMenuDistributeR, RoleMenuListR} from "@/api/role";
import {ElMessage, ElTree} from "element-plus";
import {RoleMenusListRequest, RoleMenusRequest} from "@/interface/role";
import {Menu} from "@/interface/menu";
import {MenuListR} from "@/api/menu";
import {LoadMenuTree} from "@/utils/menu";
import {TreeKey} from "element-plus/es/components/tree/src/tree.type";

const menuStore = useMenuStore()

const treeProps = {
  label: 'name',
  children: 'children',
  ifLeaf: '!!children'
}

const props = defineProps({
  role_id: {
    type: Number,
    default: 0
  }
})

const visible = ref<boolean>(true)
const checkedKeys = ref<number[]>([])

const treeRef = ref<InstanceType<typeof ElTree>>()
//菜单列表
const menus = ref<Menu[]>([])
//菜单树
const menuTree = ref<Menu[]>([])


//查询菜单列表
const getMenusTree = () => {
  MenuListR().then(res=>res.data).then(res => {
    switch (res.code) {
      case 200:
        //菜单列表=>菜单树
        let list = res.data as Menu[]
        let parents = list.filter((m) => m.parent_id === 0)
        let children = list.filter((m) => m.parent_id !== 0)
        LoadMenuTree(parents, children)
        menuTree.value = parents

        // menuTree.value = res.data as Menu[]
        menus.value = res.data as Menu[]
        break
      default:
        // ElMessage.error(res.msg)
    }
  })
}

//查询角色的菜单列表
const getRoleMenuList = () => {
  console.log('查询角色', props.role_id, '的权限列表')
  if (props.role_id < 1) {
    return
  }
  let req = <RoleMenusListRequest>({id:props.role_id})

  RoleMenuListR(req).then(res => res.data).then(res => {
    switch (res.code) {
      case 200:
        checkedKeys.value = res.data as number[]
        break
      default:
        // ElMessage.error(res.msg)
    }
  })
}

const emit = defineEmits(['close'])
//取消
const handleClose = () => {
  emit('close')
}

//节点勾选，则勾选它的父节点
const checkChange = (key:Menu, checked:boolean, deep:boolean) => {
  /*
  //只选叶子节点的值
  checkedKeys.value = treeRef.value!.getCheckedKeys(false) as number[]
  console.log('叶子节点：', JSON.stringify(checkedKeys.value))
  //只选父节点的值
  let keys = treeRef.value!.getHalfCheckedKeys() as number[]
  console.log('父节点：', JSON.stringify(keys))
  checkedKeys.value.push(...keys)

  console.log('当前选中节点：', JSON.stringify(checkedKeys.value))
  */
  if(checked){
    treeRef.value?.setChecked(key.parent_id, true, false)
    //否则(为选中状态)
    //判断父节点id是否为空
    if(key.parent_id !== 0){
      //如果不为空则将其选中
      treeRef.value?.setChecked(key.parent_id,true,false);
    }

  }else{
    //如果当前节点有子集
    if(key.children){
      //循环子集将他们的选中取消
      key.children.map(item=>{
        treeRef.value?.setChecked(item.id, false, false)
      })
    }

    /*
    console.log('当前取消节点：', key.id)
    let children = menus.value.filter((m) => m.parent_id === key.id).map((m) => m.id)
    // console.log('子节点：', children)
    let uncheckedKeys = checkedKeys.value.filter((checkedKey) => children.includes(checkedKey))
    console.log('准备取消节点：', JSON.stringify(uncheckedKeys))
    uncheckedKeys.forEach((k) => {
      console.log('取消节点：', k)
      treeRef.value?.setChecked(k, false, false)
    })
    */

  }
}

//提交
const handleSubmit = () => {
  //只选叶子节点的值
  checkedKeys.value = treeRef.value!.getCheckedKeys(false) as number[]
  console.log('叶子节点：', JSON.stringify(checkedKeys.value))
  //只选父节点的值
  let keys = treeRef.value!.getHalfCheckedKeys() as number[]
  console.log('父节点：', JSON.stringify(keys))
  checkedKeys.value.push(...keys)
  console.log('当前选中节点：', JSON.stringify(checkedKeys.value))

  let req = <RoleMenusRequest>{role_id: props.role_id, menus_id: checkedKeys.value}

  RoleMenuDistributeR(req).then(res => res.data).then(res => {
    switch (res.code) {
      case 200:
        ElMessage.success(res.msg)
        handleClose()
        break
      default:
        //ElMessage.error(res.msg)
    }
  }).catch(err => {
    ElMessage.error(err.toString())
  })
}

onMounted(() => {
  getMenusTree()
  getRoleMenuList()
})
</script>

<style scoped>

</style>